<template>
  <BaseContainer>
    <template #title>
      话务量趋势监控
    </template>
    <div class='charts-container'>
      <dv-border-box10 class="call-volume" :color="['rgba(51,172,200,.3)', 'rgba(51,172,200,.9)']" >
        <TelephoneTraffic :telephoneVolume="telephoneVolume"/>
      </dv-border-box10>
      <dv-border-box10 class="call-volume" :color="['rgba(51,172,200,.3)', 'rgba(51,172,200,.9)']" >
        <TurnOnRate :currentRate="currentRateData"/>
      </dv-border-box10>
      <dv-border-box10 class='grid-item-row call-volume' :color="['rgba(51,172,200,.3)', 'rgba(51,172,200,.9)']" >
         <line-chart :chartValue="lineChartValue" :currentMonth="peakValue.currentMonth" :historyMonth="peakValue.historyMonth"/>
      </dv-border-box10>
    </div>
  </BaseContainer>
</template>
<script setup>
import LineChart from '@/components/home/LineChart.vue';
import TelephoneTraffic from '@/components/home/TelephoneTraffic.vue';
import TurnOnRate from '@/components/home/TurnOnRate.vue';
import { BorderBox10 as DvBorderBox10 } from '@kjgl77/datav-vue3';
import {ref, onMounted, onUnmounted, reactive} from 'vue'
import { line, callValue } from '@/utils/mock.js'
import Worker from  '@/utils/worker?worker'
import Carousel from '@/utils/carousel?worker'
const loading = ref(true);
const error = ref(null);
const peakValue = reactive({
  currentMonth: 0,
  historyMonth: 0
})
// 增长率数据
let growthRateData = reactive([])
let telephoneVolumeData = reactive([])
// 呼入量和接通量数据
let telephoneVolume = ref({
	callin: 0,
	connectnum: 0
})
// 当前展示的增长率数据
let currentRateData = ref({
  time: "05:00",
  todayRate: "0.33",
  yesDayRate: "0.21"
})
const lineChartValue = reactive({
  timerange: []
}) // 柱状图数据
const roundValue = reactive({})
let workerInstance
let carouselInstance

// 开始轮播上部分的数据 默认10S轮播一次
const startCarousel = (interval) => {
  if (!carouselInstance) {
    carouselInstance = new Carousel()
  }
  carouselInstance.onmessage = (event) => {
    const { type, index } = event.data;
    if (type === 'step') {
      currentRateData.value = growthRateData[index]
    }
  }
  // 向 Web Worker 发送消息，启动定时任务
  carouselInstance.postMessage({ action: 'start', interval, startIndex: 1, length: growthRateData.length });
}
const stopRefresh = () => {
  if (workerInstance) {
    // 向 Web Worker 发送消息，停止定时任务
    workerInstance.postMessage({ action: 'stop' });
  }
}
const startRefresh = async (interval) => {
  if (!workerInstance) workerInstance = new Worker()
  workerInstance.onmessage = (event) => {
    const { type, payload } = event.data;
    if (type === 'data') {
      const [lineValue, toroidal] = payload;
      lineChartValue.value = lineValue
      roundValue.value = toroidal
      // 向 Web Worker 发送消息，停止定时任务
      if (carouselInstance) {
        carouselInstance.postMessage({ action: 'stop' });
        carouselInstance.terminate();
        carouselInstance = null;
      }
      handleFetchData()
      error.value = null;
    } else if (type === 'error') {
      error.value = payload;
      loading.value = false;
    }
  };
  // 向 Web Worker 发送消息，启动定时任务
  workerInstance.postMessage({ action: 'start', interval });
};
const handleFetchData = (dev) => {
  if (dev==='test') {
    // 初始化增长率数据
    growthRateData = line.traffiBarCharts.map(item => {
      return {
        // 时间
        time: item.timerange,
        // 呼入量较昨日增长率
        todayRate: Number(item.callnumreta),
        // 接通量较昨日增长率
        yesDayRate: Number(item.connecnumreta)
      }
    })
    // 柱状图数据
    lineChartValue.timerange = line.traffiBarCharts.map(item => item.timerange)
    // 呼入量
    lineChartValue.incomingCall = line.traffiBarCharts.map(item => item.callin)
    // 昨日呼入量
    lineChartValue.yesIncomingCall = line.traffiBarCharts.map(item => item.beforecallin)
    // 接通量
    lineChartValue.quantityAmount = line.traffiBarCharts.map(item => item.connectnum)
    // 昨日接通量
    lineChartValue.yesQuantityAmount = line.traffiBarCharts.map(item => item.beforeconnectnum)
    // 当月峰值
    peakValue.currentMonth = callValue.timerangeHis[0].countmonth
    // 历史峰值
    peakValue.historyMonth = callValue.timerangeHis[0].countmonthhistory
    // 呼入量和接通量
    telephoneVolumeData = callValue.timerange.map(item => {
      return {
        // 呼入量
        callin: Math.floor(item.callin),
        // 接通量
        connectnum: Math.floor(item.connectnum)
      }
    })
    telephoneVolume.value = telephoneVolumeData[0]
    // 轮播增长率和呼入量
    startCarousel(3000)
  } else {
    // 初始化增长率数据
    growthRateData = lineChartValue.value.traffiBarCharts.map(item => {
      return {
        // 时间
        time: item.timerange,
        // 呼入量较昨日增长率
        todayRate: Number(item.callnumreta),
        // 接通量较昨日增长率
        yesDayRate: Number(item.connecnumreta)
      }
    })
    // 柱状图数据
    lineChartValue.timerange = lineChartValue.value.traffiBarCharts.map(item => item.timerange)
    // 呼入量
    lineChartValue.incomingCall = lineChartValue.value.traffiBarCharts.map(item => item.callin)
    // 昨日呼入量
    lineChartValue.yesIncomingCall = lineChartValue.value.traffiBarCharts.map(item => item.beforecallin)
    // 接通量
    lineChartValue.quantityAmount = lineChartValue.value.traffiBarCharts.map(item => item.connectnum)
    // 昨日接通量
    lineChartValue.yesQuantityAmount = lineChartValue.value.traffiBarCharts.map(item => item.beforeconnectnum)
    // 当月峰值
    peakValue.currentMonth = roundValue.value.timerangeHis[0].countmonth
    // 历史峰值
    peakValue.historyMonth = roundValue.value.timerangeHis[0].countmonthhistory
    // 呼入量和接通量
    telephoneVolumeData = roundValue.value.timerange.map(item => {
      return {
        // 呼入量
        callin: Math.floor(item.callin),
        // 接通量
        connectnum: Math.floor(item.connectnum)
      }
    })
    telephoneVolume.value = telephoneVolumeData[0]
    // 轮播增长率
    startCarousel(5000)
  }

}
onMounted(() => {
  startRefresh(3 * 60000)
  // handleFetchData('test')
})
onUnmounted(() => {
  // 组件卸载时停止刷新并清理 Worker
  stopRefresh();
  if (workerInstance) {
    workerInstance.terminate();
    workerInstance = null;
  }
})
</script>
<style lang='less' scoped>
.charts-container {
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: calc(50% - 10px) calc(50% - 10px);
  grid-template-rows: 40% calc(60% - 20px);
  grid-gap: 20px;
  .grid-item-row {
    grid-column: 1/3;
  }
  .call-volume {
    background-image: url("@/assets/bg.png");
    background-repeat: no-repeat;
    background-size: 92%;
    background-position: center calc(100% - 30px);
  }
}
</style>
